#!/usr/bin/env python
# coding=utf-8

import os
import subprocess
import sys
import shutil
from pathlib import Path

# PROJECTS = '/home/ubuntu/Work/platformio/alientek/1，标准例程-寄存器版本'
# PROJECTS = '/home/ubuntu/Work/platformio/alientek/2，标准例程-HAL库版本'
PROJECTS = '/home/ubuntu/Work/platformio/alientek/3，扩展例程'

KEIL5PLATFORMIO = '/home/ubuntu/Work/keil2platformio/keil2platformio.py'
PIO = '/home/ubuntu/.platformio/penv/bin/pio'

def main():
    projects = Path(PROJECTS)
    if not projects.is_dir:
        print('Error: %s is not dir' % (projects))
        sys.exit(1)
    # create dir
    problem = projects.joinpath('problem')
    shutil.rmtree(problem, ignore_errors=True)
    os.mkdir(problem)
    tmp = projects.joinpath('tmp')
    shutil.rmtree(tmp, ignore_errors=True)
    os.mkdir(tmp)
    # foreach project
    files = list(projects.rglob('keilkill.bat'))
    for file in files:
        project = file.parent
        print('---------------------------------------------------')
        print(project.name)
        log = tmp.joinpath(project.name + '.log')
        # copy
        project = shutil.copytree(project, tmp.joinpath(project.name))
        # keil2platformio
        ret = subprocess.run(['python', KEIL5PLATFORMIO, project], stdout=subprocess.PIPE,stderr=subprocess.STDOUT, encoding="utf-8")
        with open(log, 'a') as f:
            f.write(ret.stdout)
        if ret.returncode:
            print(ret.stdout)
            shutil.move(project, problem)
            shutil.move(log, problem)
            continue
        # pio run
        cwd = Path.cwd()
        os.chdir(project)
        ret = subprocess.run([PIO, 'run'], stdout=subprocess.PIPE,stderr=subprocess.STDOUT, encoding="utf-8")
        os.chdir(cwd)
        with open(log, 'a') as f:
            f.write(ret.stdout)
        if ret.returncode or '[FAILED]' in ret.stdout:
            print(ret.stdout)
            shutil.move(project, problem)
            shutil.move(log, problem)
            continue
        # delet log
        os.remove(log)
        print('---------------------------------------------------')
    # delet tmp
    shutil.rmtree(tmp, ignore_errors=True)

if __name__ == '__main__':
    main()